﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Serilog;
using Serilog.Core;

namespace Nuanyang.Asp.Net.Core.Extension.Middleware
{
    public class ExceptionMiddleware
    {
        private RequestDelegate _next;
        private ILogger _log;
        private bool _printInConsole;

        /// <summary>
        /// 异常收集及异常处理
        /// </summary>
        /// <param name="next">管道下一个中间件</param>
        /// <param name="printInConsole">是否在控制台打印</param>
        /// <param name="logfileName">日志文件名</param>
        public ExceptionMiddleware(RequestDelegate next, bool printInConsole, ILogger logger)
        {
            _next = next;
            _log = logger.ForContext(typeof(ExceptionMiddleware));
            _printInConsole = printInConsole;
        }

        /// <summary>
        /// 异常收集及异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _ = HandleExceptionAsync(context, ex);
            }
        }
        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            if (ex != null)
            {
                context.Response.StatusCode = StatusCodes.Status500InternalServerError;
                //记录异常日志
                _log.Fatal("{0}", Newtonsoft.Json.JsonConvert.SerializeObject(ex));
                if (_printInConsole)
                    Console.Write(ex);
            }
            return Task.CompletedTask;
        }
    }
}
